//
//  DepoistRootVC.swift
//  d11
//
//  Created by peale on 2018/11/3.
//  Copyright © 2018年 Tech_001. All rights reserved.
//

import UIKit
import SwiftyJSON
class DepoistRootVC: BXBaseVC {
    var index : Int?
    var isCurrentH5Page : Bool = false
    var currentVC: UIViewController?
    var depoistTypeListVC :DepoistTypeListVC?
    var webViewVC : WebViewController?
    var frame :CGRect?
    var isLoad :Bool =  false
    
    // 如果需要拦截系统返回按钮就重写该方法返回 false
    override func currentViewControllerShouldPop() -> Bool {
        print("执行1")
        if isCurrentH5Page == true{
            if(self.webViewVC?.webView?.canGoBack ?? false){
                self.webViewVC?.webView?.goBack() 
            }else{
                let dialogMessage = UIAlertController(title: "提示", message: "确认离开当前页面?", preferredStyle: .alert)
                dialogMessage.view.tintColor = UIColor.black
                
                let ok = UIAlertAction(title: "确定", style: .default, handler: { (action) -> Void in
                    self.navigationController?.popViewController(animated: true)
                })
                let cancelExit = UIAlertAction(title: "取消", style: .default, handler: { (action) -> Void in
                })
                dialogMessage.addAction(ok)
                dialogMessage.addAction(cancelExit)
                
                self.tabBarController?.present(dialogMessage, animated: true, completion: nil)
            }
            return false
        }
        
        return true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 设置导航栏默认返回按钮
        self.leftButtonActionWithImg("icon_default_back")
        self.navigationItemTitleView()
        
        self.frame = self.view.bounds
        RequestHelper.makeCFCookie()
        self.depoistTypeListVC = DepoistTypeListVC()
        self.webViewVC =  WebViewController()
        self.webViewVC?.isShowRefresh = false
        self.webViewVC?.view.backgroundColor = UIColor.white
        let url = "https://" + UserDefaults.standard.string(forKey: DefaultKey.USER_DOMAIN)! + "/walletm/deposit"
        self.webViewVC?.url = url
        
        if isCurrentH5Page == true {
             self.title = ""
//            self.navigationItem.rightBarButtonItems = [UIBarButtonItem.init(image: imageNamed("icon_depoist_switch_app"),style: UIBarButtonItem.Style.plain, target: self, action: #selector(self.actionToChangePage(_:))),UIBarButtonItem.init(title: "关闭", style: UIBarButtonItem.Style.plain, target: self, action: #selector(self.actionToClose(_:)))]
            self.addChild(self.webViewVC!)
            self.webViewVC?.didMove(toParent: self)
             self.webViewVC?.signLoging = true
            self.currentVC = self.webViewVC
            self.webViewVC?.view.frame = self.frame!
            self.view.addSubview((self.webViewVC?.view)!)
        }else{
             self.title = ""
//            self.navigationItem.rightBarButtonItems = [UIBarButtonItem.init(image: imageNamed("icon_depoist_switch_H5"), style: UIBarButtonItem.Style.plain, target: self, action: #selector(self.actionToChangePage(_:)))]
            self.addChild(self.depoistTypeListVC!)
            self.depoistTypeListVC?.didMove(toParent: self)
            self.currentVC = self.depoistTypeListVC
            self.depoistTypeListVC?.view.frame = self.frame!
            self.view.addSubview((self.depoistTypeListVC?.view)!)
        }
     //   self.automaticallyAdjustsScrollViewInsets = false
    }
    
    //关闭
    @objc func actionToClose(_ sender:UIBarButtonItem) ->  Void{
        self.navigationController?.popViewController(animated: true)
    }
    
    //切换
    @objc func actionToChangePage(_ sender:UIBarButtonItem) ->  Void {
        if isLoad == true{
            
            return
        }
        var newDepositPage = "-1"
        if isCurrentH5Page == true {
            if (self.currentVC as! WebViewController)._loadView != nil {
              (self.currentVC as! WebViewController)._loadView?.removeFromSuperview()
            }
            newDepositPage = "1"
        }else
        {
            (self.currentVC as! DepoistTypeListVC).dismissLoadHUD()
            newDepositPage = "0"
        }
        self.isLoad = true
        self.showLoadHUD(title: "更新切换状态中...")
        NetWorkRequest(API.updateNewDepositPage(url: "cce782c", newDepositPage: newDepositPage), completion: { (responseData,statusCode,strData) -> (Void) in
            DispatchQueue.main.async {
                print("更新切换状态:\(responseData)")
                self.dismissLoadHUD()
                let data = responseData["data"].dictionary
                let response = data?["response"]?.dictionary ?? [:]
                let code  = response["c"]?.int ?? -1
                if code == 0{//成功
                    if newDepositPage == "1"{ //切换到原生页面
                        self.navigationItem.rightBarButtonItems = [UIBarButtonItem.init(image: imageNamed("icon_depoist_switch_H5"), style: UIBarButtonItem.Style.plain, target: self, action: #selector(self.actionToChangePage(_:)))]
                        self.isCurrentH5Page =  false
                        self.title = ""
                        sender.image = imageNamed("icon_depoist_switch_H5")
                        self.depoistTypeListVC = DepoistTypeListVC()
                        self.transitionFromOldVC(oldVC: self.currentVC!, newVC: self.depoistTypeListVC!)
                    }else if newDepositPage == "0"{ //切换到h5
                        
                        self.navigationItem.rightBarButtonItems = [UIBarButtonItem.init(image: imageNamed("icon_depoist_switch_app"),style: UIBarButtonItem.Style.plain, target: self, action: #selector(self.actionToChangePage(_:))),UIBarButtonItem.init(title: "关闭", style: UIBarButtonItem.Style.plain, target: self, action: #selector(self.actionToClose(_:)))]
                        self.isCurrentH5Page =  true
                        self.title = ""
                        sender.image = imageNamed("icon_depoist_switch_app")
                        RequestHelper.makeCFCookie()
                        
                        self.webViewVC = WebViewController.init()
                        self.webViewVC?.signLoging = true
                        self.webViewVC?.isShowRefresh = false
                        self.webViewVC?.view.backgroundColor = UIColor.white
                        let url = "https://" + UserDefaults.standard.string(forKey: DefaultKey.USER_DOMAIN)! + "/walletm/deposit"
                        self.webViewVC?.url = url
                        self.transitionFromOldVC(oldVC: self.currentVC!, newVC: self.webViewVC!)
                    }
                }else if code == 999 || code == 1150 {
                    UIHelper.displayLoginExpireTip(self)
                }else {
                    UIHelper.alertSimpleMessage(about: "发生错误:\(CodeMessageHelper.get(String(code)))", withDescription: "", in: self)
                }
                self.isLoad = false
            }
        }, failed: { (faildInfo,reCode,msg) -> (Void) in
            DispatchQueue.main.async {
                self.dismissLoadHUD()
                if reCode == "21002"{
                    UIHelper.displayLoginExpireTip(self)
                }else{
                    UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
                }
                self.isLoad = false
            }
        }) { () -> (Void) in
            DispatchQueue.main.async {
                self.dismissLoadHUD()
                UIHelper.alertSimpleMessage(about: "更新切换状态请求异常!\(getErrorString())", withDescription: "", in: self)
                self.isLoad = false
            }

        }
    }
    
    //转换子视图控制器
    func transitionFromOldVC(oldVC:UIViewController,newVC:UIViewController) -> Void{
        if self.currentVC != newVC {
            self.addChild(newVC)
            newVC.view.frame = self.frame!
            self.transition(from: oldVC, to: newVC, duration: 0.3, options: UIView.AnimationOptions.transitionCrossDissolve, animations: {
                
            }) { (finished) in
                if finished == true{
                    newVC.didMove(toParent: self)
                    oldVC.willMove(toParent: nil)
                    oldVC.removeFromParent()
                    self.currentVC = newVC;
                }
                
            }
        }
       
    }
        //移除所有子视图控制器
    func removeeAllChildVCs() -> Void {
        for (_,vc) in self.children.enumerated() {
            vc.willMove(toParent: nil)
            vc.removeFromParent()
        }
    }

  

}
